// MongoDB 初始化脚本

// 切换到 admin 数据库进行认证
db = db.getSiblingDB('admin');
db.auth('admin', 'newhand');

// 创建应用数据库
db = db.getSiblingDB('aipaper_db');

// 创建用户
db.createUser({
  user: 'aipaper_user',
  pwd: 'newhand',
  roles: [
    {
      role: 'readWrite',
      db: 'aipaper_db'
    }
  ]
});

// 创建集合和索引
db.createCollection('users');
db.users.createIndex({ email: 1 }, { unique: true });
db.users.createIndex({ username: 1 }, { unique: true });
db.users.createIndex({ createdAt: -1 });

db.createCollection('papers');
db.papers.createIndex({ title: 'text', content: 'text' });
db.papers.createIndex({ authorId: 1 });
db.papers.createIndex({ status: 1 });
db.papers.createIndex({ createdAt: -1 });

db.createCollection('sessions');
db.sessions.createIndex({ token: 1 }, { unique: true });
db.sessions.createIndex({ userId: 1 });
db.sessions.createIndex({ expireAt: 1 }, { expireAfterSeconds: 0 });

// 插入示例数据
db.users.insertOne({
  username: 'admin',
  email: 'admin@aipaper.com',
  role: 'admin',
  createdAt: new Date(),
  updatedAt: new Date()
});

print('MongoDB initialization completed successfully!');